<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">

                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="物料名称" v-if="permissionStore.hasPermisson('wllb.cx')">
                            <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading"
                            @search="handleSearchs1s1" v-model="pageData.dropDownData" :filter-option="false"
                            allow-search allow-clear @focus="focusSels1s1">
                            <a-option v-for="item in pageData.nameLists1s1 as any" :value="item.materialName">{{
                                item.materialName
                            }}
                            </a-option>
                        </a-select> -->
                            <a-input v-if="id == 1" allow-clear class="bacClass" placeholder=""
                                v-model="pageData.dropDownData" @press-enter="huiche" />
                            <a-input v-if="id == 2" allow-clear class="bacClass" placeholder=""
                                v-model="pageData.dropDownData2" @press-enter="huiche2" />
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar v-if="id == 1" :items="[
                        `${permissionStore.hasPermisson('wllb.cx') ? '查询' : ''}`,
                        `${permissionStore.hasPermisson('wllb.xz') ? '新增' : ''}`,
                        `${permissionStore.hasPermisson('wllb.sc') ? '删除' : ''}`,
                        `${permissionStore.hasPermisson('wllb.sh') ? '审核' : ''}`
                    ]" @add="addHandler" @del="deleteHandler" @select="selectHandler" @audit="audits">
                    </Toolbar>
                    <Toolbar v-if="id == 2" :items="[
                        `${permissionStore.hasPermisson('wllb.cx') ? '查询' : ''}`,
                        `${permissionStore.hasPermisson('wllb.xz') ? '新增' : ''}`,
                        `${permissionStore.hasPermisson('wllb.fs') ? '反审' : ''}`,
                        `${permissionStore.hasPermisson('wllb.cx') ? '打印二维码' : ''}`,
                        `${permissionStore.hasPermisson('wllb.dr') ? '导入' : ''}`,
                        `${permissionStore.hasPermisson('wllb.mbxz') ? '模板下载' : ''}`,
                    ]" @add="addHandler" @del="deleteHandler" @import="importHandler" @excel="downloadHandler"
                        @select="selectHandler" @counter="auditStates" @printQRCode="printQRCode">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <!-- '导出', '导入' -->
                <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
                </Toolbar> -->
            </div>
        </template>
        <template #pageTabel>

            <!-- <a-table style="height:100%" size="mini" :scrollbar="true" sticky-header
                                 @page-change="pagination.change" stripe @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}" :bordered="true"
                                 :columns="tableColumns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                 v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                                 :pagination="false"
                                 :rowKey="rowKey">
                        <template #action="{ record }">
                            <a-button type="primary" size="mini" status="warning" @click="editHandler(record)"
                                      v-if="pageData.isEdit">
                                <template #icon>
                                    <icon-edit/>
                                </template>
                                修 改
                            </a-button>
                        </template>
                    </a-table> -->
            <a-tabs   :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
                <a-tab-pane title="未审核" key="1">
                    <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
                            style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                            :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                    </a-spin>
                </a-tab-pane>
                <a-tab-pane title="已审核" key="2">
                    <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady3"
                            style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                            :rowData="table.dataList" :columnDefs="tc3" :localeText="localeText1"></AgGridVuesCopys>
                    </a-spin>
                </a-tab-pane>
            </a-tabs>
        </template>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
            :current="pagination.page" />
        <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" height="100%"
            :mask-closable="false" popup-container=".main-base-style" placement="bottom" :visible="pageData.showAdd"
            unmountOnClose @ok="sideOk" @cancel="sideNo" :ok-loading="pageData.pageLoading">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div style="height: 100%; min-width:1500px; overflow:auto;">
                <a-form ref="formRef" layout="inline" :model="dataForm" :label-col-props="{ span: 13 }"
                    :wrapper-col-props="{ span: 11 }" size="mini">

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料大类" field="bigClassName"
                        :rules="[{ required: true, message: '物料大类必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" :loading="loadings" @search="handleSearchs"
                            @change="focusSelsss" v-model="dataForm.bigClassName" :filter-option="false" allow-search
                            allow-clear @focus="focusSels">
                            <a-option v-for="item in pageData.nameLists as any" :value="item.bigClassName">{{
                                item.bigClassName
                            }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料小类" field="subClassName"
                        :rules="[{ required: true, message: '物料小类必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" @change="isDatas" allow-clear allow-search
                            v-model="dataForm.subClassName" :style="{ width: '320px' }" @focus="focusSels1">
                            <a-option v-for="item in pageData.nameLists1">{{ item.subClassName }}</a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料规格" field="subClassName">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" @focus="isDataIsfo" @change="changeName"
                            v-model="dataForm.specName" :style="{ width: '320px' }" allow-clear allow-search>
                            <a-option v-for="item in dataListGg">{{ item.specName }}</a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="编号" field="materialCode"
                        :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-input disabled class="bacClass" v-model="dataForm.materialCode" @blur="inputBlur" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="物料名称" field="materialName"
                        :rules="[{ required: true, message: '物料名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" :disabled="pageData.isDetail" v-model="dataForm.materialName" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="供应商名称">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" :loading="loadings1s1"
                            @search="handleSearchz" v-model="dataForm.providerName" :filter-option="false" allow-search
                            allow-clear @focus="focusSelz">
                            <a-option v-for="item in pageData.nameListz as any" :value="item.providerName">{{
                                item.providerName
                            }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="单位" field="unit"
                        :rules="[{ required: true, message: '单位必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" v-model="dataForm.unit"
                            @search="searchUnit" @focus="focusunit" allow-clear allow-search :filter-option="false"
                            @change="unitChanges">
                            <a-option v-for="item in pageData.unitList" :value="item['detailName']">{{
                                item["detailName"] }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="采购单位" field="purchaseUnit"
                        :rules="[{ required: true, message: '采购单位必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :disabled="pageData.isDetail" v-model="dataForm.purchaseUnit"
                            @search="searchUnit1" @focus="focusunit1" allow-clear allow-search :filter-option="false">
                            <a-option v-for="item in pageData.unitList1" :value="item['detailName']">{{
                                item["detailName"] }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="换算比例" field="convertRate"
                        :rules="[{ required: true, message: '换算比例必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input-number v-model="dataForm.convertRate" :precision="0" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :min="1" :max="1000000000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="采购单价" field="purchasePrice">
                        <a-input-number v-model="dataForm.purchasePrice" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="2" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="浓度单价" field="concentrationPrice">
                        <a-input-number v-model="dataForm.concentrationPrice" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="2" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="销售单价" field="salePrice">
                        <a-input-number v-model="dataForm.salePrice" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="2" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="安全库存" field="securityStockNum">
                        <a-input-number class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.securityStockNum" :precision="0" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="提前期" field="leadTime">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.leadTime" />
                    </a-form-item>


                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="贮存期限" field="storeTrem">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.storeTrem" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="品牌" field="brandName">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.brandName" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="经济批量" field="economicBatch">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.economicBatch" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="称料系统物料名称"
                        field="weighMaterialName">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.weighMaterialName" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="原料类型">
                        <a-select popup-container="html"  class="input-demo bacClass" :disabled="pageData.isDetail" :loading="loading"
                            @search="handleSearchzs" v-model="dataForm.rawmaterialType" :filter-option="false" allow-search
                            allow-clear @focus="focusSelzs">
                            <a-option v-for="item in pageData.nameListzs" :value="item">{{
                                item
                            }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="盈亏误差" field="profitLossError">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.profitLossError" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="生产商" field="producter">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.producter" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="化料温度"
                        field="chemicalTemperature">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.chemicalTemperature" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="化料时间" field="chemicalTime">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail"
                            v-model="dataForm.chemicalTime" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="浓度系数"
                        field="concentrationCoefficient">
                        <a-input-number v-model="dataForm.concentrationCoefficient" :precision="2"
                            class="input-demo bacClass" :disabled="pageData.isDetail" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="包装数量" field="packageNum">
                        <a-input-number v-model="dataForm.packageNum" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="0" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="税率" field="texRate">
                        <a-input-number v-model="dataForm.texRate" class="input-demo bacClass" :disabled="pageData.isDetail"
                            :precision="2" :min="0" :max="100000000" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="中文名称" field="chinessName">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.chinessName" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="外文名称" field="englishName">
                        <a-input class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.englishName" />
                    </a-form-item>

                    <a-form-item :style="{ width: '325px' }" label-col-flex="120px" label="最高库存" field="maxStockNum">
                        <a-input-number v-model="dataForm.maxStockNum" class="input-demo bacClass"
                            :disabled="pageData.isDetail" :precision="0" :min="0" :max="100000000" />
                    </a-form-item>
                    <a-form-item :style="{ width: '325px' }" field="oldNewService">
                        <el-checkbox v-model="dataForm.oldNewService" :true-label="1" :disabled="pageData.isDetail"
                            :false-label="0" style="font-size: 22px;font-weight: 600;color: #4E5969;">以旧换新</el-checkbox>
                    </a-form-item>
                    <a-form-item label-col-flex="110px" field="picture" v-if="pageData.isShow">
                        <a-upload list-type="picture-card" action="/" image-preview :limit="1"
                            :customRequest="customUpload1" style="margin-left:300px;" />
                    </a-form-item>
                    <a-form-item label-col-flex="110px" field="picture" v-if="pageData.isShow1" @click="picClick">
                        <a-image list-type="picture-card" :src="picUrl" @click="picClick" style="margin-left:300px;" />
                    </a-form-item>
                    <a-form-item label-col-flex="110px" field="picture" v-if="pageData.isShow2">
                        <a-image list-type="picture-card" :src="picUrl" style="margin-left:300px;" />
                    </a-form-item>
                    <span v-if="pageData.isShow1" style="color: red;margin-top:80px;margin-left:-20px;">*请点击修改图片</span>
                    <a-form-item style="width: 1022px;margin-top:-55px;" label-col-flex="120px" label="备注" field="remark">
                        <a-textarea class="input-demo bacClass" :disabled="pageData.isDetail" v-model="dataForm.remark"
                            :max-length="400" allow-clear show-word-limit />
                    </a-form-item>
                </a-form>
                <div style="font-size: 15px;">请选择成份：</div>
                <a-table stripe :bordered="true" :columns="tableColumnsCf" :loading="table.tableLoading"
                    :data="pageData.cfList" :rowKey="rowKey" size="mini">
                    <template #del="{ record }">
                        <icon-delete v-if="(record.partName != '') && pageData.isDetail == false"
                            style="font-size: 30px;cursor: pointer;color: red;" @click="delRow(record)" />
                    </template>
                    <template #partName="{ record }">
                        <div style="width:100%;">
                            <a-select popup-container="html"  class="input-demo bacClass" v-model="record.partName" @change="changeCf(record)"
                                @focus="focusSels1s" @search="handleSearchs1s" :loading="loading" :filter-option="false"
                                allow-search allow-clear :disabled="pageData.isDetail">
                                <a-option v-for="item in pageData.nameLists1s">{{ item.partName }}</a-option>
                            </a-select>
                        </div>
                    </template>
                    <template #ratio="{ record }">
                        <div style="width:100%">
                            <a-input-number v-model="record.ratio" class="input-demo bacClass" :min="0" :max="100"
                                @change="changeBl(record)" :disabled="pageData.isDetail" />
                        </div>
                    </template>
                </a-table>
                <!--   <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" stripe :bordered="true" rowSelection="multiple" @grid-ready="gridReady2"
                    :style="{ height: '100%' }" :defaultColDef="defaultColDef2" class='ag-theme-alpine'
                    :rowData="pageData.cfList" :columnDefs="tc2">
                </AgGridVuesCopys> -->
            </div>
        </a-drawer>
        <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭" unmountOnClose>
            <template #title> 打印二维码 </template>
            <div id="wllist" style="height: 500px;">
                <div v-for="(item, index) in qrDataList" :key="index" style="display: inline-block;margin-bottom: 10px;">
                    <QrcodeVue :value="item['code']"></QrcodeVue>
                    <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
                        <span>物料编号: {{ decodeURI(item['materialCode']) }}</span>
                        <br />
                        <span>物料名称: {{ decodeURI(item['materialName']) }}</span>
                        <br />
                    </div>
                </div>

            </div>
        </a-modal>
    </pageTabelLayout>
</template>


<script setup lang="ts" name="ListMaterialsVue">
import { post } from '@/api/http'
import { usePagination, useRowKey, useRowSelection, useTable, useTableColumn } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { onMounted, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import usePermission from '@/store/modules/permission';

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import { AnyColumn } from 'element-plus/es/components/table-v2/src/common';
import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import { log } from 'echarts/types/src/util/log';
interface ProcurementType {
    "id": any
    "uid": any
    "materialCode": any
    "materialName": any
    "bigClassName": any
    "subClassName": any
    "specName": any
    "partName": any
    "providerName": any
    "maxStockNum": any
    "unit": any
    "packageNum": any
    "securityStockNum": any
    "salePrice": any
    "leadTime": any
    "storeTrem": any
    "brandName": any
    "economicBatch": any
    "weighMaterialName": any
    "purchasePrice": any
    "texRate": any
    "concentrationPrice": any
    "rawmaterialType": any
    "profitLossError": any
    "producter": any
    "chemicalTemperature": any
    "chemicalTime": any
    "concentrationCoefficient": any
    "remark": any
    "chinessName": any
    "englishName": any
    "validState": any
    "mustVerifyState": any
    "materialImg": any
    "deleteState": any
    "createName": any
    "createTime": any
    "updateName": any
    "updateTime": any
    "purchaseUnit": any
    "convertRate": any
    "ratio": any
    subClassCode: any
    picture: string
    oldNewService: any
}

// let fileList:any = []
const total = ref(0);
const page = ref(1);
const size = ref(10);
let id = ref(1);
const handoff = (key: any) => {
    id.value = key;
    if (id.value == 1) {
        doRefresh();
    } else {
        doRefresh2();
    }
}
function PageSize(val: any) {
    if (id.value == 1) {
        pagination.page = val
        doRefresh();
    } else {
        pagination.page = val
        doRefresh2();
    }

}

function change1(val: any) {
    if (id.value == 1) {
        pagination.pageSize = val
        doRefresh();
    } else {
        pagination.pageSize = val
        doRefresh2();
    }
}

//未审核 查询
function doRefresh() {
    pageData.pageLoading = true
    post({
        url: "dwPurchase/MaterialInfo/getPage",
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            materialName: pageData.dropDownData,
            auditState: 0,
        },
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                table.handleSuccess(data.list);
                gridOption.value.setRowData(data.list);
                total.value = data.total;
            }
        })
        .catch(console.log).finally(() => {
            pageData.pageLoading = false
        })
}
//已审核 查询
function doRefresh2() {
    pageData.pageLoading = true
    post({
        url: "dwPurchase/MaterialInfo/getPage",
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            materialName: pageData.dropDownData2,
            auditState: 1,
        },
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                table.handleSuccess(data.list);
                gridOption3.value.setRowData(data.list);
                total.value = data.total;
            }
        })
        .catch(console.log).finally(() => {
            pageData.pageLoading = false
        })
}
const { selectedRowKeys, onSelectionChange } = useRowSelection();
//成分表勾选返回的id

const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
const tableColumns = useTableColumn([

    {
        title: "编号",
        key: "materialCode",
        dataIndex: "materialCode",
        width: 150
    },
    {
        title: "物料名称",
        key: "materialName",
        dataIndex: "materialName",
        width: 150
    },
    {
        title: "物料规格",
        key: "specName",
        dataIndex: "specName",
        width: 150
    },
    {
        title: "以旧换新",
        key: "oldNewService",
        dataIndex: "oldNewService",
        slotName: 'oldNewService',
        width: 150
    },
    {
        title: '图片',
        key: 'picture',
        dataIndex: 'picture',
        slotName: 'picture',
        width: 150,
    },
    {
        title: "备注",
        key: "remark",
        dataIndex: "remark",
        width: 150
    },
    {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        width: 150
    },
    {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 200
    },
    {
        title: "最后修改人",
        key: "updateName",
        dataIndex: "updateName",
        width: 150
    },
    {
        title: "最后修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
        width: 200
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right'
    }
]);
const tableColumns2 = useTableColumn([

    {
        title: "编号",
        key: "materialCode",
        dataIndex: "materialCode",
        width: 150
    },
    {
        title: "物料名称",
        key: "materialName",
        dataIndex: "materialName",
        width: 150
    },
    {
        title: "物料规格",
        key: "specName",
        dataIndex: "specName",
        width: 150
    },
    {
        title: "以旧换新",
        key: "oldNewService",
        dataIndex: "oldNewService",
        slotName: 'oldNewService',
        width: 150
    },
    {
        title: '图片',
        key: 'picture',
        dataIndex: 'picture',
        slotName: 'picture',
        width: 150,
    },
    {
        title: "备注",
        key: "remark",
        dataIndex: "remark",
        width: 150
    },
    {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        width: 150
    },
    {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 200
    },
    {
        title: "最后修改人",
        key: "updateName",
        dataIndex: "updateName",
        width: 150
    },
    {
        title: "最后修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
        width: 200
    },
    {
        title: '状态',
        key: 'obsoleteState',
        dataIndex: 'obsoleteState',
        slotName: 'obsoleteState',
        fixed: 'right',
        width: 150,
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 150,
        fixed: 'right'
    }
]);
let tc: any[] = tableColumns.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = 130
        obj['cellRenderer'] = {
            template: `<a-space><a-tag class="tagCss" @click="a1" v-if="e">修改</a-tag>
            <a-tag class="tagCss" @click="a2" v-if="f">详情</a-tag></a-space>`,
            setup(props: any) {
                const a1 = () => {
                    editHandler(props.params.data)
                }
                const a2 = () => {
                    detail(props.params.data)
                }
                return {
                    e: pageData.isEdit,
                    f: pageData.isDetail,
                    a1,
                    a2
                }
            }

        }
    }
    if (o.slotName === 'picture') {
        obj['filter'] = false
        obj['cellRenderer'] = {
            template: `<a-image :src="p" style="margin:0 auto;" />`,
            setup(props: any) {
                let p = ref()
                p.value = baseURL + props.params.data.picture
                return {
                    p,
                }
            },
        }
    }
    if (o.slotName === 'oldNewService') {
        obj['cellRenderer'] = {
            template: `<a-checkbox v-model="dataForm.oldNewService" @change="a"></a-checkbox>`,
            setup(props: any) {
                const dataForm = props.params.data
                const a = () => {
                    NewChange(props.params.data)
                }
                dataForm.oldNewService = dataForm.oldNewService == 0 ? false : true
                return {
                    a,
                    dataForm,
                }
            },
        }
        obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '未选'
          : params.value == '1'
          ? '已选'
          : ''
      },
    }
    }
    return obj
})
let tc3: any[] = tableColumns2.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = 130
        obj['cellRenderer'] = {
            template: `<a-space><a-tag class="tagCss" @click="a2" v-if="f">详情</a-tag>
            <a-tag class="tagCss" @click="c">{{b==1?'生效':'失效'}}</a-tag></a-space>`,
            setup(props: any) {
                const a2 = () => {
                    detail(props.params.data)
                }
                const c = () => {
                    updateObsoleteState(props.params.data)
                }
                return {
                    f: pageData.isDetail,
                    a2,
                    b: props.params.data.obsoleteState,
                    c,
                }
            }

        }
    }
    if (o.slotName === 'obsoleteState') {
        obj['width'] = 100
        obj['cellRenderer'] = {
            template: `<el-tag v-if="isDatas.obsoleteState == 0" type="success">生效
                        </el-tag>
                        <el-tag v-if="isDatas.obsoleteState == 1" type="danger">失效
                        </el-tag>
                        `,
            setup(props: any) {
                const isDatas = ref(props.params.data)
                return {
                    isDatas,
                }
            },
        }
    }
    if (o.slotName === 'picture') {
        obj['cellRenderer'] = {
            template: `<a-image :src="p" style="margin:0 auto;" />`,
            setup(props: any) {
                let p = ref()
                p.value = baseURL + props.params.data.picture
                return {
                    p,
                }
            },
        }
    }
    if (o.slotName === 'oldNewService') {
        obj['cellRenderer'] = {
            template: `<a-checkbox v-model="val" disabled></a-checkbox>`,
            setup(props: any) {
                let val = ref()
                val.value = props.params.data.oldNewService == 0 ? false : true
                return {
                    val,
                }
            },
        }
    }
    return obj
})

let a = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
}]
tc = a.concat(tc)
tc3 = a.concat(tc3)

const detail = (record: ProcurementType) => {
    pageData.isDetail = true
    pageData.cfList = [];
    let list = record.partName.split('/');
    for (let i = 0; i < list.length; i++) {
        var ob = {};
        ob['partName'] = list[i].split(',')[0]
        ob['ratio'] = list[i].split(',')[1] == "" ? 0 : parseFloat(list[i].split(',')[1])
        pageData.cfList.push(ob)
    }

    for (let key in record) {
        dataForm[key] = record[key]
    }
    pageData.isShow2 = true
    pageData.isShow1 = false
    pageData.isShow = false
    picUrl.value = baseURL + record.picture
    pageData.sideTitle = '物料列表明细'
    pageData.showAdd = true
}
//成分信息表格
const tableColumnsCf = useTableColumn([
    {
        title: "操作",
        key: "del",
        dataIndex: "del",
        slotName: 'del',
        width: 150,
    },
    {
        title: "成分",
        key: "partName",
        dataIndex: "partName",
        slotName: 'partName',
        width: 150,
    },

    {
        title: "比例",
        key: "ratio",
        dataIndex: "ratio",
        slotName: 'ratio',
        width: 150,
    },

]);
let tc2: any[] = tableColumnsCf.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    obj['width'] = 250
    if (o.slotName === 'del') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 80
        obj["lockPosition"] = "left"
        obj['cellRenderer'] = {
            template: `<icon-delete v-if="e" style="font-size: 30px;cursor: pointer;color: red;"
                            @click="delClick" />`,
            setup(props: any) {
                const record = ref(props.params.data)
                const delClick = () => {
                    delRow(props.params.data)
                }
                return {
                    e: record.partName != '',
                    delClick, record
                }
            }

        }
    }
    if (o.slotName === 'partName') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 300
        // obj["lockPosition"] = "right"
        obj['cellRenderer'] = {
            template: `<a-select popup-container="html"  class="bacClass" v-model="record.partName" @change="partChange"
                                @focus="focusSels1s" @search="handleSearchs1s" :loading="loading" :filter-option="false"
                                allow-search allow-clear>
                                <a-option v-for="item in val">{{ item.partName }}</a-option>
                            </a-select>`,
            setup(props: any) {
                const record = ref(props.params.data)
                let val = ref()
                val.value = pageData.nameLists1s
                const partChange = () => {
                    changeCf(props.params.data)
                }
                //下拉框得到焦点
                const focusSels1s = () => {
                    selCxAlls1s({ partName: '' })
                }
                //下拉数据
                const optionss1s = ref<any>(pageData.nameLists1s);
                const loadings1s = ref(false);
                const handleSearchs1s = (value: any) => {
                    if (value) {
                        const ob = { partName: value }
                        loadings1s.value = true;
                        selCxAlls1s(ob);
                        optionss1s.value = pageData.nameLists1s;
                        loadings1s.value = false;
                    } else {
                        optionss1s.value = []
                    }
                };
                //下拉框查询
                function selCxAlls1s(val: any) {
                    post({
                        url: "dwPurchase/MaterialPart/getFieldValue",
                        data: val
                    }).then(({ data, code }: any) => {
                        if (code === 200) {
                            pageData.nameLists1s = data;
                        } else {
                        }
                    });
                }
                return {
                    record,
                    partChange,
                    val,
                    focusSels1s,
                    handleSearchs1s,
                    selCxAlls1s,
                }
            }

        }
    }
    if (o.slotName === 'ratio') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 300
        // obj["lockPosition"] = "right"
        obj['cellRenderer'] = {
            template: `<a-input-number v-model="record.ratio" class="input-demo bacClass" :min="0" :max="100"
                        @change="ratioChange" />`,
            setup(props: any) {
                const record = ref(props.params.data)
                const ratioChange = () => {
                    changeBl(props.params.data)
                }
                return {
                    record,
                    ratioChange
                }
            }

        }
    }
    return obj
})



let a2 = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
}]
tc2 = a2.concat(tc2)

const pageData = reactive<{
    nameList: [],
    nameLists: [],
    nameLists1: [],
    nameLists1s: any[],
    nameLists1s1: [],
    nameListz: [],
    nameListzs: [],
    showAdd: boolean,
    sideTitle: string,
    dropDownData: any,
    pageLoading: boolean,
    rHeight: any,
    btnList: any[],
    isEdit: boolean,
    cfList: any[],
    unitList: [],
    unitList1: [],
    dropDownData2: any,
    isDetail: boolean,
    file: string,
    isShow: boolean,
    isShow1: boolean,
    isShow2: boolean,
}>({
    isShow2: false,
    isShow1: false,
    isShow: false,
    file: '',
    nameList: [],
    nameLists: [],
    nameLists1: [],
    nameLists1s: [],
    nameLists1s1: [],
    nameListz: [],
    nameListzs: [],
    showAdd: false,
    sideTitle: '新增物料列表',
    dropDownData: "",
    pageLoading: false,
    rHeight: "",
    btnList: [],
    isEdit: false,
    cfList: [],
    unitList: [],
    unitList1: [],
    dropDownData2: "",
    isDetail: false
});
//下拉框得到焦点
const focusSel = () => {
    selCxAll({ specName: '' })
}
//下拉数据
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
    if (value) {
        const ob = { specName: value }
        loading.value = true;
        window.setTimeout(() => {
            selCxAll(ob);
            options.value = pageData.nameList;
            loading.value = false;
        }, 200)
    } else {
        options.value = []
    }
};

//下拉框查询
function selCxAll(val: any) {
    post({
        url: "dwPurchase/MaterialSpec/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameList = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

onMounted(() => {
    emitter.on("ListMaterials", () => {
        if (id.value == 1) {
            doRefresh();
        } else {
            doRefresh2();
        }
    });
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //表格的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight
        //表格的高
        if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight;
        }
    })
});
//查询
const selectHandler = () => {
    if (id.value == 1) {
        pagination.page = 1
        doRefresh();
    } else {
        pagination.page = 1
        doRefresh2();
    }
}
const addHandler = () => {
    pageData.cfList = [];
    pageData.isShow = true
    pageData.isDetail = false
    //清空数据
    for (const key in dataForm) {
        if (key == "id") {
            dataForm.id = null;
        } else if (key == "maxStockNum" ||
            key == "packageNum" ||
            key == "securityStockNum" ||
            key == "salePrice" ||
            key == "purchasePrice" ||
            key == "texRate" ||
            key == "concentrationPrice" ||
            key == "concentrationCoefficient") {
            dataForm[key] = 0;
        } else if (key == "convertRate") {
            dataForm[key] = 1;
        }
        else {
            dataForm[key] = '';
        }
    }
    focusSels1s()
    pageData.showAdd = true
    pageData.sideTitle = '新增物料列表'
    pageData.cfList.push({ "partName": "", "ratio": 0 })

}

const dataForm = reactive<ProcurementType>({
    "id": "",
    "uid": "",
    "materialCode": "",
    "bigClassName": "",
    "materialName": "",
    "subClassName": "",
    "specName": "",
    "partName": "",
    "providerName": "",
    "maxStockNum": 0,
    "unit": "",
    "packageNum": 0,
    "securityStockNum": 0,
    "salePrice": 0,
    "leadTime": "",
    "storeTrem": "",
    "brandName": "",
    "economicBatch": "",
    "weighMaterialName": "",
    "purchasePrice": 0,
    "texRate": 0,
    "concentrationPrice": 0,
    "rawmaterialType": "",
    "profitLossError": "",
    "producter": "",
    "chemicalTemperature": "",
    "chemicalTime": "",
    "concentrationCoefficient": 0,
    "remark": "",
    "chinessName": "",
    "englishName": "",
    "validState": "",
    "mustVerifyState": "",
    "materialImg": "",
    "deleteState": "",
    "createName": "",
    "createTime": "",
    "updateName": "",
    "updateTime": "",
    "purchaseUnit": '',
    "convertRate": 1,
    "ratio": "",
    subClassCode: "",
    picture: '',
    oldNewService: '',
})

// 表格准备事件
//未审核
const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}
const gridOption2 = ref()
const gridReady2 = (params: any) => {
    gridOption2.value = params.api
}
//已审核
const gridOption3 = ref()
const gridReady3 = (params: any) => {
    gridOption3.value = params.api
}
const formRef = ref<FormInstance>()
const sideOk = () => {
    // console.log(fileList)
    formRef.value?.validate().then((err) => {
        if (!err) {
            //将成份拼接到后台
            dataForm.partName = '';
            let isCf = false
            pageData.cfList.forEach(function (o: any) {
                if (o['partName'] != '' && o['ratio'] != 0) {
                    if (dataForm.partName == '') {
                        dataForm.partName = o['partName'] + ',' + o['ratio']
                    } else {
                        dataForm.partName += '/' + o['partName'] + ',' + o['ratio']
                    }
                }
            })
            if (pageData.sideTitle === "新增物料列表") {
                pageData.pageLoading = true
                dataForm.id = null
                dataForm.materialImg = null
                if (pageData.file != '') {
                    let fd = new FormData()
                    fd.append('file', pageData.file)
                    axios.post(baseURL + '/minio/file/upload', fd, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            token: sessionStorage.getItem('USER-TOKEN-KEY'),
                        },
                    })
                        .then((res: any) => {
                            dataForm.picture = res['data']['data']['data']
                            if (res.code == 500) {
                                Message.error(res.message)
                            }
                            post({
                                url: 'dwPurchase/MaterialInfo/insert',
                                data: [dataForm],
                            })
                                .then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields()
                                        pageData.showAdd = false
                                        Message.success({
                                            content: '新增成功',
                                            duration: 5000,
                                        })
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        })
                                    }
                                })
                                .finally(() => {
                                    doRefresh()
                                    pageData.pageLoading = false
                                })
                        })
                } else {
                    post({
                        url: "dwPurchase/MaterialInfo/insert",
                        data: [dataForm],
                    }).then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            if (id.value == 1) {
                                doRefresh();
                            } else {
                                doRefresh2();
                            }
                            Message.success({
                                content: "新增成功",
                                duration: 5000,
                            });
                        } else {
                            Message.error({
                                content: res.message,
                                duration: 5000,
                            });
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    })
                }

            } else if (pageData.sideTitle === "修改物料列表") {
                dataForm.materialImg = null
                if (pageData.isShow = true) {
                    let fd = new FormData()
                    fd.append('file', pageData.file)
                    axios.post(baseURL + '/minio/file/upload', fd, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            token: sessionStorage.getItem('USER-TOKEN-KEY'),
                        },
                    })
                        .then((res: any) => {
                            dataForm.picture = res['data']['data']['data']
                            if (res.code == 500) {
                                Message.error(res.message)
                            }
                            post({
                                url: 'dwPurchase/MaterialInfo/update',
                                data: [dataForm],
                            })
                                .then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields()
                                        pageData.showAdd = false
                                        Message.success({
                                            content: '修改成功',
                                            duration: 5000,
                                        })
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        })
                                    }
                                    //doRefresh();
                                })
                                .finally(() => {
                                    doRefresh()
                                    pageData.pageLoading = false
                                })
                        })
                }
                else {
                    post({
                        url: "dwPurchase/MaterialInfo/update",
                        data: [dataForm],
                    }).then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            if (id.value == 1) {
                                doRefresh();
                            } else {
                                doRefresh2();
                            }
                            //清空数据
                            for (const key in dataForm) {
                                if (key == "id") {
                                    dataForm.id = null;
                                } else {
                                    dataForm[key] = '';
                                }
                            }
                            Message.success({
                                content: "修改成功",
                                duration: 5000,
                            });
                        } else {
                            Message.error({
                                content: res.message,
                                duration: 5000,
                            });
                        }
                    });
                }
            }
        }
    });
}

const sideNo = () => {
    pageData.showAdd = false
    pageData.isShow1 = false
    pageData.isShow2 = false
    pageData.isShow = false
    picUrl.value = ""
}
const deleteHandler = () => {
    if (gridOption.value.getSelectedRows().length === 0 && gridOption3.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            if (id.value == 1) {
                post({
                    url: 'dwPurchase/MaterialInfo/delete',
                    data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                }).then(({ code, message }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: '删除成功',
                            duration: 5000
                        })
                        page.value = 1
                        doRefresh()
                    } else {
                        Message.success({
                            content: message,
                            duration: 5000
                        })
                    }
                })
            } else {
                post({
                    url: 'dwPurchase/MaterialInfo/delete',
                    data: gridOption3.value.getSelectedRows().map((o: any) => { return o.id })
                }).then(({ code, message }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: '删除成功',
                            duration: 5000
                        })
                        page.value = 1
                        doRefresh2()
                    } else {
                        Message.error({
                            content: message,
                            duration: 5000
                        })
                    }
                })
            }

        }
    })
}
let picUrl = ref()
const editHandler = (record: ProcurementType) => {
    pageData.isDetail = false
    pageData.cfList = [];
    let list = record.partName.split('/');
    for (let i = 0; i < list.length; i++) {
        var ob = {};
        ob['partName'] = list[i].split(',')[0]
        ob['ratio'] = list[i].split(',')[1] == "" ? 0 : parseFloat(list[i].split(',')[1])
        pageData.cfList.push(ob)
    }
    for (let key in record) {
        dataForm[key] = record[key]
    }
    dataForm.oldNewService = record.oldNewService == false ? 0 : 1
    if (record.picture != "") {
        pageData.isShow1 = true
        pageData.isShow = false
        pageData.isShow2 = false
        picUrl.value = baseURL + record.picture
    } else {
        pageData.isShow1 = false
        pageData.isShow2 = false
        pageData.isShow = true
    }
    // pageData.isShow = true
    dataForm.id = Number(record.id);
    pageData.sideTitle = '修改物料列表'
    pageData.showAdd = true
};
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
    return new Promise<void>(resolve => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
        }
        resolve()
    })

}
//input离开焦点 将小写转大写
const inputBlur = () => {
    dataForm.materialCode = dataForm.materialCode.toUpperCase();
}

//下拉框得到焦点
const focusSels = () => {
    selCxAlls({ bigClassName: '' })
}
//下拉数据
const optionss = ref<any>(pageData.nameLists);
const loadings = ref(false);
const handleSearchs = (value: any) => {
    if (value) {
        const ob = { bigClassName: value }
        loadings.value = true;
        window.setTimeout(() => {
            selCxAlls(ob);
            optionss.value = pageData.nameLists;
            loadings.value = false;
        }, 200)
    } else {
        optionss.value = []
    }
};

//下拉框查询
function selCxAlls(val: any) {
    post({
        url: "dwPurchase/MaterialBigClass/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameLists = data;
        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

//下拉框得到焦点
const focusSels1 = () => {
    selCxAlls1({ subClassName: '' })
}
//下拉数据
const optionss1 = ref<any>(pageData.nameLists1);
const loadings1 = ref(false);
const handleSearchs1 = (value: any) => {
    if (value) {
        const ob = { subClassName: value }
        loadings1.value = true;
        window.setTimeout(() => {
            selCxAlls1(ob);
            optionss1.value = pageData.nameLists1;
            loadings1.value = false;
        }, 200)
    } else {
        optionss1.value = []
    }
};

//下拉框查询
function selCxAlls1(val: any) {
    if (dataForm.bigClassName == "") {
        Message.error('请先选择物料大类!')
        return
    }
    post({
        url: "dwPurchase/MaterialSubClass/getFieldValue",
        data: {
            bigClassName: dataForm.bigClassName
        }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameLists1 = data;
        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

//下拉框得到焦点
const focusSels1s = () => {
    selCxAlls1s({ partName: '' })
}
//下拉数据
const optionss1s = ref<any>(pageData.nameLists1s);
const loadings1s = ref(false);
const handleSearchs1s = (value: any) => {
    if (value) {
        const ob = { partName: value }
        loadings1s.value = true;

        selCxAlls1s(ob);
        optionss1s.value = pageData.nameLists1s;
        loadings1s.value = false;

    } else {
        optionss1s.value = []
    }
};

//下拉框查询
function selCxAlls1s(val: any) {
    post({
        url: "dwPurchase/MaterialPart/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameLists1s = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}


//下拉框得到焦点
const focusSels1s1 = () => {
    selCxAlls1s1({ materialName: '' })
}
//下拉数据
const optionss1s1 = ref<any>(pageData.nameLists1s1);
const loadings1s1 = ref(false);
const handleSearchs1s1 = (value: any) => {
    if (value) {
        const ob = { materialName: value }
        loadings1s1.value = true;
        window.setTimeout(() => {
            selCxAlls1s1(ob);
            optionss1s1.value = pageData.nameLists1s1;
            loadings1s1.value = false;
        }, 200)
    } else {
        optionss1s1.value = []
    }
};

//下拉框查询
function selCxAlls1s1(val: any) {
    post({
        url: "dwPurchase/MaterialInfo/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameLists1s1 = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

//下拉框得到焦点
const focusSelz = () => {
    selCxAllz({ providerName: '' })
}
//下拉数据
const optionsz = ref<any>(pageData.nameListz);
const loadingz = ref(false);
const handleSearchz = (value: any) => {
    if (value) {
        const ob = { providerName: value }
        loadingz.value = true;
        window.setTimeout(() => {
            selCxAllz(ob);
            optionsz.value = pageData.nameListz;
            loadingz.value = false;
        }, 200)
    } else {
        optionsz.value = []
    }
};

//下拉框查询
function selCxAllz(val: any) {
    post({
        url: "dwPurchase/Provider/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameListz = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

//下拉框得到焦点
const focusSelzs = () => {
    selCxAllzs({ materialsCategoryName: '', deleteState: 0 })
}
//下拉数据
const optionszs = ref<any>(pageData.nameListzs);
const loadingzs = ref(false);
const handleSearchzs = (value: any) => {
    if (value) {
        const ob = { materialsCategoryName: value, deleteState: 0 }
        loadingzs.value = true;
        selCxAllzs(ob);
        optionszs.value = pageData.nameListzs;
        loadingzs.value = false;
    } else {
        options.value = []
    }
};

//下拉框查询
function selCxAllzs(val: any) {
    post({
        url: "product/RawmaterialType/getDrop",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameListzs = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

const headerShow = ref<boolean>(true)

let dataListXl = ref<any[]>([])

const focusSelsss = (val: any) => {
    dataForm.subClassName = ''
    dataForm.materialCode = ''
    post({
        url: 'dwPurchase/MaterialSubClass/getFieldValue',
        data: {
            bigClassName: val
        }
    }).then((res: any) => {
        if (res.code == 200) {
            dataListXl.value = res.data
        } else {
            Message.error('获取物料小类失败')
        }
    })
}

const code = (val: any) => {
    post({
        url: 'dwPurchase/MaterialSubClass/getFieldValue',
        data: {
            subClassName: val
        }
    }).then((res: any) => {
        if (res.code == 200) {
            dataListXl.value = res.data
            var code = res.data[0].encoding
            post({
                url: '/dwPurchase/MaterialInfo/getMaxCode',
                data: {
                    encoding: code
                }
            }).then(({ code, data }: any) => {
                if (code == 200) {
                    dataForm.materialCode = data.maxApplyCode
                }
            })
        } else {
            Message.error('获取物料小类失败')
        }
    })
}

let dataListGg = ref<any[]>([])

let dataListXls = ''
const isDatas = (val: any) => {
    post({
        url: 'dwPurchase/MaterialSpec/getList',
        data: {
            subClassName: val,
        }
    }).then((res: any) => {
        if (res.code == 200) {
            // dataListGg = res.data
        } else {
            Message.error('获取物料规格失败')
        }
    })
    dataListXls = val
    dataForm.materialName = dataForm.subClassName + "" + ((dataForm.specName == null || dataForm.specName == "") ? "" : dataForm.specName);
    dataForm.subClassCode = dataForm.subClassCode
    code(val)
}
const changeName = (val: any) => {
    dataForm.materialName = dataForm.subClassName + "" + ((dataForm.specName == null || dataForm.specName == "") ? "" : dataForm.specName);

}
let dataListCf = ref<any[]>([])

const isDataIsfo = (val: any) => {
    post({
        url: 'dwPurchase/MaterialSpec/getFieldValue',
        data: {
            specName: ""
        }
    }).then((res: any) => {
        if (res.code == 200) {
            dataListGg = res.data
            console.log(res.data);

        } else {
            Message.error('获取物料成分失败')
        }
    })
    // dataForm.materialName = dataListXls + val
}
//成份删除
const delRow = (record: any) => {
    if (pageData.cfList.length !== 1) {
        pageData.cfList = pageData.cfList.filter(function (o: any) {
            return o['partName'] !== record['partName']
        })
    } else {
        Message.warning('最后一条数据，不可删除！')
    }

}
//判断是否有重复
const changeCf = (record: any) => {
    let count1 = 0;
    let count2 = 0;
    record.ratio = 0;
    for (let index = 0; index < pageData.cfList.length; index++) {
        const element = pageData.cfList[index];
        if (element['partName'] == record['partName']) {
            count1++
        }
        if (element['partName'] == '') {
            count2++;
        }
        if (count1 > 1) {
            Message.warning('此成份已被选择过，请重新选择！')
            record['partName'] = ""
            return
        }
    }
    //选择完成份给用户再新增一行
    if (count2 == 0) {
        pageData.cfList.push({ "partName": "", "ratio": 0 })
        // console.log(1111111111111);

    }
}
//判断比例列是否大于100
const changeBl = (record: any) => {
    setTimeout(function () {
        let num = 0;
        pageData.cfList.forEach(function (o: any) {
            if (o['partName'] != '' && o['ratio'] != undefined && o['ratio'] != null && o['ratio'] != '') {
                console.log(parseFloat(o['ratio']));
                num += parseFloat(o['ratio']);
            }
        })
        if (num > 100) {
            Message.warning('此比率列已超过100,请重新填写！')
            record['ratio'] = 0
        }
    }, 100);

}
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('wllb.xg')) {
    pageData.isEdit = true
}
if (permissionStore.hasPermisson('wllb.xq')) {
    pageData.isDetail = true
}
const focusunit = () => {
    getUnitList("")
};
// 单位下拉框
const searchUnit = (value: any) => {
    if (value) {
        loading.value = true;
        getUnitList(value);
        options.value = pageData.unitList;
        loading.value = false;
    } else {
        options.value = []
    }
};
// 单位下拉框
const getUnitList = (val: any) => {
    post({
        url: 'dict/dictTypeDetail/getListByMap',
        data: {
            codeType: 17,
            detailName: val
        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            pageData.unitList = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });
};


const focusunit1 = () => {
    getUnitList1("")
};
// 单位下拉框
const searchUnit1 = (value: any) => {
    if (value) {
        loading.value = true;
        getUnitList1(value);
        options.value = pageData.unitList1;
        loading.value = false;
    } else {
        options.value = []
    }
};
// 单位下拉框
const getUnitList1 = (val: any) => {
    post({
        url: 'dict/dictTypeDetail/getListByMap',
        data: {
            codeType: 17,
            detailName: val
        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            pageData.unitList1 = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });
};
const handleChange = (_data: any) => {
    table.handleSuccess(_data);
};
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
}
const defaultColDef2 = {
    sortable: true,
    resizable: true,
    filter: true,
}
//回车查询
const huiche = () => {
    selectHandler()
}
const huiche2 = () => {
    selectHandler()
}
//审核按钮
const audits = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return;
    }
    let ids: any = []
    gridOption.value.getSelectedRows().forEach((item: any) => {
        ids.push({
            id: item.id,
        })
    })
    Modal.confirm({
        title: '系统提示',
        content: '是否审核此单号',
        onOk() {
            post({
                url: "/dwPurchase/MaterialInfo/audit",
                data: {
                    id: ids,
                    auditState: 1,
                },
            }).then((res: any) => {
                if (res.code === 200) {
                    doRefresh();
                    Message.success('审核通过')
                } else {
                    Message.error(res.message)
                }
            })
        }
    })
}
//反审按钮
const auditStates = () => {
    if (gridOption3.value.getSelectedRows().length === 0) {
        Message.error('请勾选需要反审的数据')
        return
    }
    let ids: any = []
    gridOption3.value.getSelectedRows().forEach((item: any) => {
        ids.push({
            id: item.id,
        })
    })
    Modal.confirm({
        title: '系统提示',
        content: '是否反审此订单',
        onOk() {
            post({
                url: '/dwPurchase/MaterialInfo/audit',
                data: {
                    id: ids,
                    auditState: 0,
                },
            }).then((res: any) => {
                if (res.code === 200) {
                    doRefresh2()
                    //   emitter.emit('shauxings')
                    Message.success('反审成功')
                } else {
                    Message.error(res.message)
                }
            })
        },
    })
}
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
//模板下载
const downloadHandler = () => {
    axios.get(baseURL + '/dwPurchase/MaterialInfo/uploadModel', {
        responseType: 'blob',
        headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY')
        }
    }).then((res) => {
        if (res.status === 200) {
            filedownload(res.data, '物料列表.xlsx')
        }
    })
}
//导入
const importHandler = () => {

    const inputEle: HTMLInputElement = document.createElement('input')
    inputEle.type = 'file'
    inputEle.id = 'fileUploadExcel'
    inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
    inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
        } else {
            Message.warning('未选择文件！');
            return
        }
        pageData.pageLoading = true
        axios.post(baseURL + '/dwPurchase/MaterialInfo/importModelData', formData, {
            headers: {
                "Content-Type": 'multipart/form-data',
                "token": sessionStorage.getItem('USER-TOKEN-KEY')
            },
        }).then((result) => {
            if (result.data['code'] === 200) {
                Message.success('导入成功')
            } else {
                Message.error(result.data.message)
            }

        }).finally(() => {
            pageData.pageLoading = false
            doRefresh2()
        })
    })
    inputEle.click()
}
const unitChanges = (e: any) => {
    if (dataForm.purchaseUnit == '') {
        dataForm.purchaseUnit = e
    }
}
//生效不生效
function updateObsoleteState(record: any) {
    Modal.confirm({
        title: '系统提示',
        content: '是否继续订单进行操作',
        onOk() {
            let state = null
            if (record.obsoleteState == 1) {
                state = 1
            } else {
                state = 0
            }
            post({
                url: '/dwPurchase/MaterialInfo/updateObsoleteState',
                data: {
                    id: record.id,
                    obsoleteState: state
                }
            }).then((res: any) => {
                if (res.code === 200) {
                    doRefresh2()
                    Message.success('成功！')
                } else {
                    Message.error(res.message)
                }
            })
        }
    })

}

let qrDataList = ref([])
const visible = ref(false)

const handleOk = () => {
    printJS({
        printable: 'wllist',
        type: 'html',
        targetStyles: ['*'],
    })
    visible.value = false
}
const handleCancel = () => {
    visible.value = false
}
//打印二维码
const printQRCode = () => {
    if (gridOption3.value.getSelectedRows().length === 0) {
        Message.error('请勾选需要打印的数据')
        return
    }
    visible.value = true
    let row = gridOption3.value.getSelectedRows()
    row.forEach(function (o: any) {
        let ob = {}
        ob['materialCode'] = o['materialCode']
        ob['materialName'] = o['materialName']
        ob['code'] = JSON.stringify({
            materialCode: encodeURI(o.materialCode)

        })
        qrDataList.value.push(ob)
    })
}

//文件上传
function customUpload1(info: any) {
    info.onSuccess('')
    pageData.file = info.fileItem.file
    return info
}

const picClick = () => {
    pageData.isShow = true
    pageData.isShow1 = false
    pageData.isShow2 = false
}

const NewChange = (record: any) => {
    post({
        url: '/dwPurchase/MaterialInfo/updateOldNew',
        data: {
            id: record.id,
            oldNewService: record.oldNewService == false ? 0 : 1
        }
    }).then((res: any) => {
        if (res.code === 200) {
            doRefresh()
        } else {
            Message.error(res.message)
        }
    })
}
</script>

<style lang="less">
.arco-image-img {
    width: 80px;
    height: 80px;
    margin-left: 600px;
    margin: 0 auto;
}

div.arco-image-error {
    width: 80px;
    height: 80px;
    margin-left: 600px;
    margin: 0 auto;
}
</style>